package com.dhecp.project.storage.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.beust.jcommander.internal.Lists;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dhecp.common.config.Global;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.DateUtils;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.core.utils.ScreenValueMergeStrategy;
import com.dhecp.project.business.domain.FbaLogsticsOrderBox;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.logstics.mapper.FbaLogsticsOrderBoxMapper;
import com.dhecp.project.storage.domain.*;
import com.dhecp.project.storage.mapper.TsCustomsclearanceMapper;
import com.dhecp.project.storage.mapper.TsCustomsclearancedetailMapper;
import com.dhecp.project.storage.mapper.TsCustomsclearancesonMapper;
import com.dhecp.project.storage.service.TsCustomsclearanceService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 报关单(TsCustomsclearance表)服务实现类
 *
 * @author fxz
 * @since 2024-01-15 10:02:56
 */
@Service("tsCustomsclearanceService")
public class TsCustomsclearanceServiceImpl extends BaseModuleServiceImpl implements TsCustomsclearanceService {
    @Autowired
    private TsCustomsclearanceMapper tsCustomsclearanceMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private TsCustomsclearancedetailMapper tsCustomsclearancedetailMapper;

    @Autowired
    private FbaLogsticsOrderBoxMapper fbaLogsticsOrderBoxMapper;

    @Autowired
    private TsCustomsclearancesonMapper tsCustomsclearancesonMapper;
    /**
     * 通过guid查询单条数据
     *
     * @param params 对象
     * @return 实例对象
     */
    @Override
    public TsCustomsclearance queryFirstRecord(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return this.tsCustomsclearanceMapper.selectFirstRecordByNid(params);
    }

    /**
    * 查询列表数据
    */
    @Override
    public List<TsCustomsclearance> queryList(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.createTime DESC";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }
        if (params.get("type") != null){
            if (params.get("type").equals("0")){
                params.put("state","t1.state = '无'");
            }else {
                params.put("state","t1.state != '无'");
            }
        }else {
            params.put("state","t1.state = '无'");
        }
        return this.tsCustomsclearanceMapper.select(params);
    }

    /**
     * 报关调用数据
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<TsCustomesSelect> queryListSelect(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句

        PageUtils.startPage();

        return tsCustomsclearanceMapper.queryListSelect(params);
    }

    /**
     * 获取详情列表
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<TsCustomsclearancedetail> queryList3(Map<String, Object> params) throws Exception {
        List<TsCustomsclearancedetail> tsCustomsclearancedetailList = new ArrayList<>();
        List<TsCustomesSelect> onSonData = JSON.parseArray(params.get("res").toString(), TsCustomesSelect.class);
        List<FbaLogsticsOrderBox> fbaLogsticsOrderBoxListNew = null;
        BigDecimal numRealityDeliver;
        JSONArray boxListNew;
        List<BigDecimal> boxList;
        int numbox = 0;
        for (TsCustomesSelect tsCustomesSelect : onSonData){
            //判断是物流订单还是海外仓入库单
            if (tsCustomesSelect.getCode().contains("WLDD")){
                TsCustomsclearancedetail tsCustomsclearancedetailNew;
                params.put("codeFbaLogsticsOrder",tsCustomesSelect.getCode());
                //查询订单箱子数据
                List<FbaLogsticsOrderBox > fbaLogsticsOrderBoxList = fbaLogsticsOrderBoxMapper.findFbaLogsticsOrderBox(params);
                for (FbaLogsticsOrderBox fbaLogsticsOrderBox : fbaLogsticsOrderBoxList){
                    numbox++;
                    //根据库存id 获取对应的采购订单信息
                    fbaLogsticsOrderBoxListNew = JSON.parseArray(fbaLogsticsOrderBox.getProductInfo(), FbaLogsticsOrderBox.class);
                    for (FbaLogsticsOrderBox fbaLogsticsOrderBoxNew :fbaLogsticsOrderBoxListNew){
                        numRealityDeliver = BigDecimal.ZERO;
                        if (fbaLogsticsOrderBoxNew.getBoxList() == null) {
                            numRealityDeliver = numRealityDeliver.add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver())
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver1().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver1()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver2().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver2()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver3().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver3()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver4().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver4()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver5().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver5()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver6().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver6()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver7().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver7()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver8().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver8()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver9().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver9()))
                                    .add(new BigDecimal(fbaLogsticsOrderBoxNew.getNumRealityDeliver10().equals("") ? "0" : fbaLogsticsOrderBoxNew.getNumRealityDeliver10()))
                            );
                        }else {
                            boxListNew = JSONArray.parseArray(fbaLogsticsOrderBoxNew.getBoxList());
                            boxList = JSONArray.parseArray(boxListNew.toJSONString(), BigDecimal.class);
                            numRealityDeliver = numRealityDeliver.add(boxList.get(fbaLogsticsOrderBox.getBoxIndex()));
                        }
                        if (numRealityDeliver.compareTo(BigDecimal.ZERO) != 0){
                            //就是这个箱子有数据
                            TsCustomsclearancedetail tsCustomsclearancedetail = tsCustomsclearancedetailMapper.list3(fbaLogsticsOrderBoxNew.getGuidKc());
                            //设置对应的值
                            tsCustomsclearancedetailNew = new TsCustomsclearancedetail();
                            tsCustomsclearancedetailNew.setLogisticsorder(tsCustomesSelect.getCode());
                            tsCustomsclearancedetailNew.setPurchaseorder(tsCustomsclearancedetail.getPurchaseorder());
                            tsCustomsclearancedetailNew.setCommoditycode(fbaLogsticsOrderBoxNew.getCommodityCode());
                            tsCustomsclearancedetailNew.setCommodityname(fbaLogsticsOrderBoxNew.getName());
                            tsCustomsclearancedetailNew.setSourcesupply(tsCustomsclearancedetail.getSourcesupply());
                            tsCustomsclearancedetailNew.setSpmcgg(tsCustomsclearancedetail.getSpmcgg());
                            tsCustomsclearancedetailNew.setDeclarationelements(tsCustomsclearancedetail.getDeclarationelements());
                            tsCustomsclearancedetailNew.setCodehs(tsCustomsclearancedetail.getCodehs());
                            tsCustomsclearancedetailNew.setPrice2(tsCustomsclearancedetail.getPrice2());
                            tsCustomsclearancedetailNew.setNameunit(tsCustomsclearancedetail.getNameunit());
                            tsCustomsclearancedetailNew.setSizeweight(tsCustomsclearancedetail.getSizeweight());
                            tsCustomsclearancedetailNew.setQuantityshipped(numRealityDeliver.intValue());
                            tsCustomsclearancedetailNew.setWeightreal(Double.valueOf(fbaLogsticsOrderBox.getWeight()));
                            tsCustomsclearancedetailNew.setWeightvol(Double.valueOf(fbaLogsticsOrderBox.getWeightVol()));
                            tsCustomsclearancedetailNew.setLength(fbaLogsticsOrderBox.getLength());
                            tsCustomsclearancedetailNew.setWidth(fbaLogsticsOrderBox.getWidth());
                            tsCustomsclearancedetailNew.setHeight(fbaLogsticsOrderBox.getHeight());
                            tsCustomsclearancedetailNew.setPackSize(fbaLogsticsOrderBox.getLength() + "*" + fbaLogsticsOrderBox.getWidth() + "*" + fbaLogsticsOrderBox.getHeight());
                            tsCustomsclearancedetailNew.setNetweight((new BigDecimal(tsCustomsclearancedetail.getSizeweight()).multiply(numRealityDeliver)).setScale(2,RoundingMode.HALF_UP).doubleValue());
                            tsCustomsclearancedetailNew.setMersurement(((new BigDecimal(fbaLogsticsOrderBox.getLength())
                                    .multiply(new BigDecimal(fbaLogsticsOrderBox.getWidth()))
                                    .multiply(new BigDecimal(fbaLogsticsOrderBox.getHeight())))
                                    .divide(new BigDecimal(1000000),2, RoundingMode.HALF_UP)).doubleValue());
                            tsCustomsclearancedetailNew.setBgprice(tsCustomsclearancedetail.getPrice2() * 1.02);
                            tsCustomsclearancedetailNew.setBgtolprice(tsCustomsclearancedetailNew.getBgprice() * tsCustomsclearancedetailNew.getQuantityshipped());
                            tsCustomsclearancedetailNew.setNumbox(numbox);
                            tsCustomsclearancedetailList.add(tsCustomsclearancedetailNew);
                        }
                    }
                }

            }else if (tsCustomesSelect.getCode().contains("HWWL")){
                List<TsCustomsclearancedetail> tsCustomsclearancedetailList1 = tsCustomsclearancedetailMapper.list2(tsCustomesSelect.getCode());
                for (TsCustomsclearancedetail tsCustomsclearancedetailNew : tsCustomsclearancedetailList1){
                    numbox++;
                    tsCustomsclearancedetailNew.setNumbox(numbox);
                    tsCustomsclearancedetailList.add(tsCustomsclearancedetailNew);
                }
            }
        }
        return tsCustomsclearancedetailList;
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new TsCustomsclearance());
        AjaxResult ajaxResult = this.saveDataBase(params);
        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        String resNid = infoMap.get("nid").toString();
        TsCustomsclearance tsCustomsclearance = JSON.parseObject(params.get("infoMap").toString(), TsCustomsclearance.class);
        List<TsCustomsclearancedetail> detailData = new ArrayList<>();
        if (params.containsKey("sonData")){
            detailData = JSON.parseArray(params.get("sonData").toString(), TsCustomsclearancedetail.class);
        }
        List<TsCustomsclearanceson> onSonData = new ArrayList<>();
        if (params.containsKey("infoItems")){
            onSonData = JSON.parseArray(params.get("infoItems").toString(), TsCustomsclearanceson.class);
        }
        List<RecordCheck> guidMapList = tsCustomsclearanceMapper.findRecords(resNid);

        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()){
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList){
                if (recordCheck != null && recordCheck.getGuid() != null){
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }
        if (onSonData == null || onSonData.size() == 0){
            resNid = "0";
        }else{
            resNid = infoMap.get("nid").toString();
            String guid = "";
            if (tsCustomsclearance.getGuid() == null){
                guid = RandomValueUtils.getGUID();
                tsCustomsclearance.setGuid(guid);
            }else{
                guid = tsCustomsclearance.getGuid().toString();
            }
            for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                Object fieldValue = infoMap.get(field);
                ReflectUtils.setValue(tsCustomsclearance, field, fieldValue);
            }

            if (guidMap.get(guid) == null){
                tsCustomsclearance.setState("无");
                tsCustomsclearance.setDerivedstate("无");
                tsCustomsclearanceMapper.insert(tsCustomsclearance);
            }else{
                tsCustomsclearanceMapper.update(tsCustomsclearance);
                guidMap.remove(guid);
                //删除详情和明细
                tsCustomsclearancedetailMapper.deleteCode(tsCustomsclearance.getBid());
                tsCustomsclearancesonMapper.deleteCode(tsCustomsclearance.getBid());
            }

            //新增详情和明细
            for (TsCustomsclearancedetail item : detailData
            ) {
                item.setGuid(RandomValueUtils.getGUID());
                item.setPcode(tsCustomsclearance.getBid());
                tsCustomsclearancedetailMapper.insert(item);
            }

            for (TsCustomsclearanceson item : onSonData
            ) {
                item.setGuid(RandomValueUtils.getGUID());
                item.setPcode(tsCustomsclearance.getBid());
                item.setCreatetime(new Date());
                tsCustomsclearancesonMapper.insert(item);
            }

        }
        if (!guidMap.isEmpty()){
            for (String guid : guidMap.keySet()){
                tsCustomsclearanceMapper.delete(guid);
                //删除详情和明细
                tsCustomsclearancedetailMapper.deleteCode(tsCustomsclearance.getBid());
                tsCustomsclearancesonMapper.deleteCode(tsCustomsclearance.getBid());
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }


    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == ""){
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = tsCustomsclearanceMapper.selectLastNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = tsCustomsclearanceMapper.selectNextNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }



    /**
     * 流转  —— 添加流程任务、修改流程状态及生效标志
     * @param tableDataId 必要参数：单据编码（nid）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<TsCustomsclearance> businessDataList = tsCustomsclearanceMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (TsCustomsclearance businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            tsCustomsclearanceMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * 退回  —— 添加流程任务、修改流程状态及生效标志
     * @param tableDataId 必要参数：单据编码（nid）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<TsCustomsclearance> businessDataList = tsCustomsclearanceMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            if (!businessDataList.get(0).getState().equals("无")){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("选择单据状态不允许重置,请核实后在操作!");
            }
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (TsCustomsclearance businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            tsCustomsclearanceMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }


    /**
     * 审核
     * @param params
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult shbtn(Map<String, Object> params) {
        if (params.get("infoItems") == null || params.get("infoItems") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack.infoItems"));
        }
        List<TsCustomsclearance> list = JSON.parseArray(params.get("infoItems").toString(), TsCustomsclearance.class);
        Set<String> nidList = new HashSet<>();
        for (TsCustomsclearance tsCustomsclearance : list){
            nidList.add(tsCustomsclearance.getNid());
        }
        for (String nid : nidList){
            params.put("nid",nid);
            TsCustomsclearance tsCustomsclearance1 = tsCustomsclearanceMapper.selectFirstRecordByNid(params);
            if (tsCustomsclearance1 == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("报关单不存在,请核实后在操作!");
            }
            if(params.get("type").equals("0")){
                if (!tsCustomsclearance1.getState().equals("无")){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("选择单据状态已变动,请核实后在操作!");
                }
                tsCustomsclearance1.setState("已审核");
            }else {
                if (tsCustomsclearance1.getState().equals("无") || tsCustomsclearance1.getState().equals("已完成")){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("选择单据状态不允许回退,请核实后在操作!");
                }
                tsCustomsclearance1.setState("无");
                tsCustomsclearance1.setDerivedstate("无");
            }
            tsCustomsclearanceMapper.update(tsCustomsclearance1);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * 报关单导出
     * @param params
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult export2(Map<String, Object> params, HttpServletResponse response) {
        String filePath = "";
        TsCustomsclearance tsCustomsclearance = null;
        try {
            //查询报关单数据
            List<TsCustomsclearance> tsCustomsclearanceList = tsCustomsclearanceMapper.select(params);
            if (tsCustomsclearanceList.size() > 0){
                tsCustomsclearance = tsCustomsclearanceList.get(0);
                //打开模板
                String templateFilePath = Global.getProfile() + "/store_template1.xls";
//            String templateFilePath = "C:\\Users\\Administrator\\Desktop\\store_template1.xls";
                //需要生成的文件名称
//            filePath = "C:\\Users\\Administrator\\Desktop\\download\\11.xls";
                filePath = Global.getProfile() + "/download/"+ tsCustomsclearance.getBid()+ ".xls";
                ExcelWriter excelWriter = EasyExcel.write(filePath).withTemplate(templateFilePath).build();

                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                WriteSheet writeSheet1 = EasyExcel.writerSheet(1).build();
                WriteSheet writeSheet2 = EasyExcel.writerSheet(2).build();
                WriteSheet writeSheet3 = EasyExcel.writerSheet(3).registerWriteHandler(new ScreenValueMergeStrategy(1)).build();
                Map<String,Object> excelDataMap = new HashMap<String, Object>();
                excelDataMap.put("productionsales", tsCustomsclearance.getProductionsales());
                excelDataMap.put("productionsalesen", tsCustomsclearance.getProductionsalesen());
                excelDataMap.put("shippingmark", tsCustomsclearance.getShippingmark());
                excelDataMap.put("contractno", tsCustomsclearance.getContractno());
                excelDataMap.put("createTime", DateUtils.parseDateToStr("yyyy-MM-dd",tsCustomsclearance.getCreateTime()));
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(tsCustomsclearance.getCreateTime());
                calendar.add(Calendar.DAY_OF_MONTH, 6);
                Date resultDate = calendar.getTime();
                excelDataMap.put("createTime1", DateUtils.parseDateToStr("yyyy-MM-dd",resultDate));
                excelDataMap.put("loadingport", tsCustomsclearance.getLoadingport());
                excelDataMap.put("destinationaddress", tsCustomsclearance.getDestinationaddress());
                excelDataMap.put("foreignconsignee",tsCustomsclearance.getForeignconsignee());
                excelDataMap.put("shippingtype", tsCustomsclearance.getShippingtype());
                excelDataMap.put("supervisionmethod",tsCustomsclearance.getSupervisionmethod());
                excelDataMap.put("naturetaxation", tsCustomsclearance.getNaturetaxation());
                excelDataMap.put("destinationcountry",tsCustomsclearance.getDestinationcountry());
                excelDataMap.put("kindpackage",tsCustomsclearance.getKindpackage());
                excelDataMap.put("numbox",tsCustomsclearance.getNumbox());
                excelDataMap.put("roughweight",tsCustomsclearance.getRoughweight());
                excelDataMap.put("netweight",tsCustomsclearance.getNetweight());
                excelDataMap.put("termsdelivery",tsCustomsclearance.getTermsdelivery());

                Double dw4 = 0.0;
                Double dw5 = 0.0;
                List<Map<String, Object>> dataList = Lists.newArrayList();
                List<Map<String, Object>> dataList1 = Lists.newArrayList();
                int i=0;
                //计算详情的总计
                for (TsCustomsclearance tsCustomsclearance1 :tsCustomsclearanceList){
                    dw4 = dw4 + (tsCustomsclearance1.getSizeweight() * tsCustomsclearance1.getQuantityshipped());
                    dw5 = dw5 + tsCustomsclearance1.getMersurement();
                    i++;

                    //设置表格数据
                    Map<String, Object> params1 = new HashMap<>();
                    params1.put("spmcgg",tsCustomsclearance1.getSpmcgg());
                    params1.put("shippingmark", tsCustomsclearance1.getShippingmark());
                    params1.put("numbox",1);
                    params1.put("quantityshipped",tsCustomsclearance1.getQuantityshipped());
                    params1.put("price2",tsCustomsclearance1.getBgprice());
                    params1.put("commoditycode", tsCustomsclearance1.getCommoditycode());
                    params1.put("weightreal",tsCustomsclearance1.getWeightreal());
                    params1.put("netweight",(tsCustomsclearance1.getNetweight1()));
                    params1.put("mersurement",tsCustomsclearance1.getMersurement());
                    params1.put("nameunit",tsCustomsclearance1.getNameunit());
                    params1.put("bgprice",tsCustomsclearance1.getBgprice());
                    params1.put("bgtolprice",tsCustomsclearance1.getBgtolprice());
                    params1.put("sourcesupply",tsCustomsclearance1.getSourcesupply());
                    params1.put("destinationcountry",tsCustomsclearance1.getDestinationcountry());
                    params1.put("zm","照章征税");
                    params1.put("bt1","");
                    params1.put("amount",(tsCustomsclearance1.getBgtolprice()));
                    dataList.add(params1);

                    params1 = new HashMap<>();
                    params1.put("numbox1",i);
                    params1.put("quantityshipped",tsCustomsclearance1.getQuantityshipped());
                    params1.put("commoditycode", tsCustomsclearance1.getCommoditycode());
                    params1.put("bgtolprice",null);
                    params1.put("price2",tsCustomsclearance1.getBgprice());
                    params1.put("commodityname",tsCustomsclearance1.getCommodityname());
                    params1.put("nameunit",tsCustomsclearance1.getNameunit());
                    params1.put("rnb","人民币");
                    params1.put("cn","中国");
                    params1.put("sourcesupply",tsCustomsclearance1.getSourcesupply());
                    params1.put("destinationcountry",tsCustomsclearance1.getDestinationcountry());
                    params1.put("zm","照章征税");
                    params1.put("bt1","");
                    dataList1.add(params1);

                    //第二条
                    params1 = new HashMap<>();
                    params1.put("numbox1",tsCustomsclearance1.getSpmcgg());
                    params1.put("commoditycode", tsCustomsclearance1.getSpmcgg());
                    params1.put("bt2",tsCustomsclearance1.getSpmcgg());
                    params1.put("commodityname",tsCustomsclearance1.getSpmcgg());
                    params1.put("price2",tsCustomsclearance1.getBgtolprice());
                    params1.put("quantityshipped","");
                    params1.put("nameunit","");
                    params1.put("cn","");
                    params1.put("bt1","");
                    params1.put("destinationcountry","");
                    params1.put("sourcesupply","");
                    params1.put("zm","");
                    params1.put("rnb","人民币");
                    dataList1.add(params1);
                }
                excelDataMap.put("dw1",tsCustomsclearanceList.size());
                excelDataMap.put("dw3",tsCustomsclearance.getRoughweight());
                excelDataMap.put("dw4",dw4);
                excelDataMap.put("dw5",dw5);
                excelDataMap.put("amountTol",tsCustomsclearance.getAmountdeclared());
                excelWriter.fill(excelDataMap,writeSheet);
                excelWriter.fill(excelDataMap,writeSheet1);
                excelWriter.fill(excelDataMap,writeSheet2);
                excelWriter.fill(excelDataMap,writeSheet3);

                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                excelWriter.fill(new FillWrapper(dataList), fillConfig, writeSheet);
                excelWriter.fill(new FillWrapper(dataList), fillConfig, writeSheet1);
                excelWriter.fill(new FillWrapper(dataList), fillConfig, writeSheet2);
                excelWriter.fill(new FillWrapper("data1",dataList1), fillConfig, writeSheet3);
                excelWriter.finish();

                //修改导出状态
                if (!tsCustomsclearance.getDerivedstate().equals("已导出")){
                    tsCustomsclearance.setDerivedstate("已导出");
                    tsCustomsclearanceMapper.update(tsCustomsclearance);
                }
            }else {
                return AjaxResult.error("数据异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(tsCustomsclearance.getBid()+ ".xls");
    }
}

